package com.thilux.lame.file;

import java.io.File;
import java.io.IOException;

import com.thilux.lame.global.LameSystemProperties;
import com.thilux.lame.logging.log4j.LameLogger;

public class LameFile extends File {

	/**
     * 
     */
	private static final long serialVersionUID = -3170509713487710799L;

	private String getDirNameOnly() {

		String[] partsFromPath = getAbsolutePath().split(LameSystemProperties.getFileSeparator());

		if (partsFromPath.length == 1) {
			return getAbsolutePath();
		} else {

			return getAbsolutePath().replaceAll(
					partsFromPath[partsFromPath.length - 1], "");

		}

	}

	private void createMissingDirsOnPath(String path) {

		LameLogger.logDebug("Creating missing directories for path %s", path);

		String[] pathParts = path.split(LameSystemProperties.getFileSeparator());

		StringBuilder subPath = new StringBuilder();

		for (String part : pathParts) {

			subPath.append(part);
			subPath.append(LameSystemProperties.getFileSeparator());

			LameLogger.logDebug("Checking part [%s]", subPath.toString());

			File dir = new File(subPath.toString());
			if (!dir.exists()) {
				LameLogger.logDebug("Creating subdir [%s] result [%s]",
						dir.getAbsolutePath(), dir.mkdir());
				// dir.mkdir();
			}

		}

	}

	@Override
	public boolean createNewFile() throws IOException {

		if (!isDirectory() && !exists()) {

			LameLogger.logDebug("[%s] is not a directory and does not exist.",
					getAbsolutePath());
			// File directory = new File(getDirNameOnly());

			createMissingDirsOnPath(getDirNameOnly());

			/*
			 * if (!directory.exists()){
			 * LameLogger.logDebug("[%s] directory doesn't exist.",
			 * directory.getAbsolutePath());
			 * 
			 * LameLogger.logDebug("File creation [%s]", directory.mkdir());
			 * if(directory.mkdir()){
			 * LameLogger.logDebug("Created directory [%s]!",
			 * directory.getAbsolutePath()); } }
			 */
		}

		return super.createNewFile();
	}

	public LameFile(String fileName) {
		super(fileName);
	}

}
